import Utils from './utils';
import HttpRequest from './HttpRequest';
import { HttpStatus } from './HttpStatus';
import { HttpFactory, HttpFail, HttpOverdue, HttpSuccess } from './HttpFactory'
const utils = new Utils();
// 自定义插件
export default {
    install(app: any, options: any) {
        // 创建请求实例
        app.config.globalProperties.$http = HttpRequest.getInstance({
            baseUrl: utils.getBaseUrl(),
        })
        // 请求拦截
        app.config.globalProperties.$http.interceptors.request((config: any) => {
            let BASE_DATA = {
                user_id: 0,
                sessid:  '',
                api:'i_1600152352',
                version: '999.999.999',
            };
            let security_key = '*&^$%#%%$&#@';
            config.data = {
                ...config.data,
                ...BASE_DATA,
            };
            config.data['sign'] = utils.setSign(config.data, security_key).getSign();
            return config;
        });
        // 响应拦截
        app.config.globalProperties.$http.interceptors.response((response: any) => {
            const { data } = response;
            if (!data) return false;
            if (data.iRet == HttpStatus.SUCCESS) {
                const httpFactory: HttpFactory = new HttpSuccess();
                return httpFactory.response(data);
            } else if (data.iRet == HttpStatus.FAIL) {
                const httpFactory: HttpFactory = new HttpFail();
                httpFactory.response(data);
            } else if (data.iRet == HttpStatus.SESSION_EXPIRATION) {
                const httpFactory: HttpFactory = new HttpOverdue();
                httpFactory.response(data);
            } else {
                return response;
            }
        })
    }
}